package com.gomore.opple.module.main.mine;

import android.app.AlertDialog;
import android.graphics.Bitmap;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventPhoto;
import com.gomore.opple.model.EventReflashLotteriedFragment;
import com.gomore.opple.model.EventReleshMine;
import com.gomore.opple.module.BaseFragmentV4;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.rest.applybill.ApplyRequest;
import com.gomore.opple.rest.applybill.EarningsResponse;
import com.gomore.opple.rest.employee.LoginResult;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.utils.BlurBitmapUtils;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.web.cgform.applybill.entity.TOApplyBillEntity;
import com.gomore.opple.web.cgform.bankcard.entity.TOBankCardEntity;
import com.gomore.opple.widgets.RoundImageView;
import com.gomore.opple.widgets.dialog.ConfirmDialog;

import java.io.File;
import java.math.BigDecimal;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by asus on 2017/5/9.
 */
public class MineFragment extends BaseFragmentV4 implements MineContract.View {

    @Bind(R.id.modify_password)
    LinearLayout modify_password;
    @Bind(R.id.mOriginImg)
    ImageView mOriginImg;
    @Bind(R.id.mBluredImage)
    ImageView mBluredImage;
    @Bind(R.id.round_icon)
    RoundImageView round_icon;
    @Bind(R.id.income_and_expense)
    LinearLayout income_and_expense;
    @Bind(R.id.my_bank)
    LinearLayout my_bank;
    @Bind(R.id.total)
    TextView total;
    @Bind(R.id.return_total)
    TextView return_total;
    @Bind(R.id.return_unuse)
    TextView return_unuse;
    @Bind(R.id.return_apply)
    TextView return_apply;
    @Bind(R.id.award_total)
    TextView award_total;
    @Bind(R.id.award_unuse)
    TextView award_unuse;
    @Bind(R.id.award_apply)
    TextView award_apply;

    @Bind(R.id.my_card)
    LinearLayout my_card;
    @Bind(R.id.my_award)
    LinearLayout my_award;
    @Bind(R.id.my_redpackage)
    LinearLayout my_redpackage;

    @Bind(R.id.logout)
    TextView logout;
    private MineContract.Presenter mPresenter;
    /**
     * 模糊后的图片
     */
    private Bitmap mFinalBitmap;

    public static MineFragment getInstance() {
        return new MineFragment();
    }

    @Override
    protected void initalizeData() {
        super.initalizeData();
        EventBus.getDefault().register(this);
        mPresenter.prepareInitData();
        mPresenter.getTotal();
    }

    @Override
    protected void initalizeViews() {
        super.initalizeViews();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_mine;
    }

    @Override
    public void showProgressDialog() {
        DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void showIcon(String url) {
        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .placeholder(R.mipmap.consumer_icon)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(round_icon);

        Glide.with(getActivity())
                .load(url)
                .asBitmap()
                .centerCrop()
                .placeholder(R.mipmap.consumer_icon)
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(mBluredImage);
    }

    @Override
    public void showContentView(EarningsResponse earningsResponse) {
        if (earningsResponse.getAccountTotal() != null && earningsResponse.getRedPackageAccountTotal() != null) {
            BigDecimal total1 = earningsResponse.getAccountTotal().add(earningsResponse.getRedPackageAccountTotal());
            total.setText("¥ " + BigDecimalUtils.forMate(total1).toString());
            return_total.setText("¥ " + BigDecimalUtils.forMate(earningsResponse.getAccountTotal()).toString());
            award_total.setText("¥ " + BigDecimalUtils.forMate(earningsResponse.getRedPackageAccountTotal()).toString());
        }
        if (earningsResponse.getApplytotal() != null) {
            return_unuse.setText("¥ " + BigDecimalUtils.forMate(earningsResponse.getApplytotal()).toString());
        }
        if (earningsResponse.getRedPackageApplytotal() != null) {
            award_unuse.setText("¥ " + BigDecimalUtils.forMate(earningsResponse.getRedPackageApplytotal()).toString());
        }
    }

    @Override
    public void showApplyAfaterDialog(final String applyId) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.apply_after_dialog, null);
        TextView confirm = (TextView) layout.findViewById(R.id.confirm);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到提现进度详情页
                mPresenter.getDetailState(applyId);
                alertDialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void gotoLoginActivity() {
        IntentStart.getInstance().startLoginActivity(getActivity());
    }

    @Override
    public void goToApplyDetail(TOApplyBillEntity toApplyBillEntity) {
        IntentStart.getInstance().startApplyDetailActivity(getActivity(), toApplyBillEntity);
    }

    @Override
    public void setPresenter(MineContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @OnClick({R.id.modify_password, R.id.round_icon, R.id.income_and_expense, R.id.my_bank, R.id.return_apply, R.id.award_apply,
            R.id.my_card, R.id.my_award, R.id.my_redpackage, R.id.my_order, R.id.logout})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.modify_password:
                showModifyPasswordDialog(mPresenter.getUser());
                break;
            case R.id.round_icon:
                IntentStart.getInstance().startTakeAndSelectPhotoActivity(getActivity(), GlobalConstant.FragmentType.MINEFRAGMENT, 0);
                break;
            case R.id.income_and_expense:
                IntentStart.getInstance().startIncomeAndExpenseActivity(getActivity());
                break;
            case R.id.my_bank:
                if (mPresenter.getData() == null) {
                    return;
                }
                if (mPresenter.getData().getBankCards().size() == 0) {
                    IntentStart.getInstance().startAddBankCarActivity(getActivity());
                } else {
                    TOBankCardEntity toBankCardEntity = mPresenter.getData().getBankCards().get(0);
                    if (toBankCardEntity != null) {
                        showDeleteBankDialog(toBankCardEntity);
                    }
                }
                break;
            case R.id.return_apply:
                if (mPresenter.getData().getApplytotal() == null) {
                    return;
                }
                if (mPresenter.getData().getBankCards().size() == 0) {
                    showMessage("您还没有绑定银行卡");
                    return;
                }
                TOBankCardEntity toBankCardEntity = mPresenter.getData().getBankCards().get(0);
                showApplyDialog(GlobalConstant.applyType.COMMISSION, mPresenter.getData().getAccountTotal(), toBankCardEntity);
                break;
            case R.id.award_apply:
                if (mPresenter.getData().getRedPackageApplytotal() == null) {
                    return;
                }
                if (mPresenter.getData().getBankCards().size() == 0) {
                    showMessage("您还没有绑定银行卡");
                    return;
                }
                TOBankCardEntity toBankCardEntity1 = mPresenter.getData().getBankCards().get(0);
                showApplyDialog(GlobalConstant.applyType.REDPACKAGE, mPresenter.getData().getRedPackageAccountTotal(), toBankCardEntity1);
                break;
            case R.id.my_card:
                IntentStart.getInstance().startCardsActivity(getActivity());
                break;
            case R.id.my_award:
                IntentStart.getInstance().startAwardActivity(getActivity());
                break;
            case R.id.my_redpackage:
                IntentStart.getInstance().startRedPackageActivity(getActivity());
                break;
            case R.id.my_order:
                IntentStart.getInstance().startOrderActivity(getActivity());
                break;
            case R.id.logout:
                //确定框
                ConfirmDialog.onNoOnclickListener onNoOnclickListener = null;
                ConfirmDialog.onYesOnclickListener onYesOnclickListener = null;
                final String title = "提示";
                String message = "确定退出登录吗?";
                onYesOnclickListener = new ConfirmDialog.onYesOnclickListener() {
                    @Override
                    public void onYesClick() {
                        mPresenter.logout();
                    }
                };
                onNoOnclickListener = new ConfirmDialog.onNoOnclickListener() {
                    @Override
                    public void onNoClick() {
                        DialogUtils.cancel();
                    }
                };
                DialogUtils.showConfirmDialog(getActivity(), onYesOnclickListener, onNoOnclickListener, title, message);
                break;
        }
    }

    /**
     * 添加银行卡之后刷新
     *
     * @param eventReleshMine
     */
    public void onEventMainThread(EventReleshMine eventReleshMine) {
        if (eventReleshMine != null && eventReleshMine.isReflash()) {
            mPresenter.getTotal();
        }
    }

    /**
     * 大转盘抽奖之后刷新
     *
     * @param eventReflashLotteriedFragment
     */
    public void onEventMainThread(EventReflashLotteriedFragment eventReflashLotteriedFragment) {
        if (eventReflashLotteriedFragment != null && eventReflashLotteriedFragment.isReflash()) {
            mPresenter.getTotal();
        }
    }

    public void onEventMainThread(EventPhoto eventPhoto) {
        if (eventPhoto != null && eventPhoto.getFragmentType() != null &&
                eventPhoto.getUrl() != null) {
            if (eventPhoto.getFragmentType().equals(GlobalConstant.FragmentType.MINEFRAGMENT)) {
                Glide.with(getActivity())
                        .load(eventPhoto.getUrl())
                        .asBitmap()
                        .placeholder(R.mipmap.consumer_icon)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(round_icon);

                Glide.with(getActivity())
                        .load(eventPhoto.getUrl())
                        .asBitmap()
                        .centerCrop()
                        .placeholder(R.mipmap.consumer_icon)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(mBluredImage);
                //上传图片
                File file = new File(eventPhoto.getUrl());
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
                mPresenter.saveAttachment(body);
            }
        }
    }

    private void showDeleteBankDialog(final TOBankCardEntity toBankCardEntity) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.delete_bank_dialog, null);
        TextView bank_name = (TextView) layout.findViewById(R.id.bank_name);
        TextView car_number = (TextView) layout.findViewById(R.id.car_number);
        TextView cancel = (TextView) layout.findViewById(R.id.cancel);
        TextView confirm = (TextView) layout.findViewById(R.id.confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        if (toBankCardEntity.getBankCardType() != null) {
            bank_name.setText(toBankCardEntity.getBankCardType());
        }
        if (toBankCardEntity.getBankAccount() != null) {
            String cardNumber = toBankCardEntity.getBankAccount();
            String cardNumber1 = cardNumber.substring(0, 4);
            String cardNumber2 = cardNumber.substring(cardNumber.length() - 4, cardNumber.length());
            car_number.setText(cardNumber1 + "****" + cardNumber2);
        }
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (toBankCardEntity.getBankAccount() != null) {
                    mPresenter.deleteBankCard(toBankCardEntity.getBankAccount());
                }
                alertDialog.dismiss();
            }
        });
    }

    private void showApplyDialog(final String type, final BigDecimal TotalBigDecimal, final TOBankCardEntity toBankCardEntity) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.apply_dialog, null);
        final EditText apply_editText = (EditText) layout.findViewById(R.id.apply_editText);
        TextView apply_confirm = (TextView) layout.findViewById(R.id.apply_confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(true);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        apply_editText.setHint("当前可提现: " + BigDecimalUtils.forMate(TotalBigDecimal).toString());
        apply_editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString().trim())) {
                    if (s.toString().trim().equals("0") || s.toString().trim().equals(".")) {
                        apply_editText.setText("");
                    }
                }
            }
        });

        apply_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(apply_editText.getText().toString().trim())) {
                    showMessage("请输入提现金额");
                    return;
                }
                BigDecimal applyBigdecimal = new BigDecimal(apply_editText.getText().toString().trim());
                int com = TotalBigDecimal.compareTo(BigDecimalUtils.forMate(applyBigdecimal));
                if (com == -1) {
                    showMessage("提现金额不能大于总金额");
                    return;
                }
                if (type.equals(GlobalConstant.applyType.REDPACKAGE)) {
                    int com1 = applyBigdecimal.compareTo(new BigDecimal(10));
                    if (com1 == -1) {
                        showMessage("提现金额不能小于10元");
                        return;
                    }
                }
                ApplyRequest applyRequest = new ApplyRequest();
                applyRequest.setBillType(type);
                applyRequest.setAmount(BigDecimalUtils.forMate(applyBigdecimal));
                applyRequest.setBankCardNumber(toBankCardEntity.getBankAccount());
                mPresenter.applySave(applyRequest);
                alertDialog.dismiss();
            }
        });
    }

    private void showModifyPasswordDialog(LoginResult loginResult) {
        View layout = LayoutInflater.from(getActivity()).inflate(R.layout.modify_password_dialog, null);

        final EditText user_name = (EditText) layout.findViewById(R.id.user_name);
        final EditText old_password = (EditText) layout.findViewById(R.id.old_password);
        final EditText new_password = (EditText) layout.findViewById(R.id.new_password);

        TextView dialog_cancel = (TextView) layout.findViewById(R.id.dialog_cancel);
        TextView dialog_confirm = (TextView) layout.findViewById(R.id.dialog_confirm);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(layout);
        builder.setCancelable(false);
        final AlertDialog alertDialog = builder.create();
        alertDialog.show();
        if (loginResult != null && loginResult.getEmployee() != null &&
                loginResult.getEmployee().getUserName() != null) {
            user_name.setText(loginResult.getEmployee().getUserName());
            user_name.setSelection(loginResult.getEmployee().getUserName().length());
        }
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        dialog_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(user_name.getText().toString().trim())) {
                    showMessage("请输入用户名");
                    return;
                }
                if (TextUtils.isEmpty(old_password.getText().toString().trim())) {
                    showMessage("请输入旧密码");
                    return;
                }
                if (TextUtils.isEmpty(new_password.getText().toString().trim())) {
                    showMessage("请输入新密码");
                    return;
                }
                if (new_password.getText().toString().trim().length() < 6
                        || new_password.getText().toString().trim().length() > 18) {
                    showMessage("新密码长度为6-18位");
                    return;
                }
                mPresenter.modifyPassword(old_password.getText().toString().trim(), new_password.getText().toString().trim());
                alertDialog.dismiss();
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
